(function () {
	//获取平台管理对象
	const yyastk = window.getYYASTK();
	//获取当前场景管理对象
	const currentScenario = yyastk.CurrentScenario;
	var VModel = {
		targeted: {
			html: "",
			value: ""
		},
		// 星座类型(Delta,Star,Custom),缺省为:Delta
		// Delta: 各轨道面的RAAN在0°-360°内均布
		// Star: 各轨道面的RAAN在0°-180°内均布
		// Custome: 用户指定轨道面RAAN的间隔
		WalkerType: "Delta",
		WalkerTypes: [
			{
				name: "Delta",
				value: "Delta"
			},
			{
				name: "Star",
				value: "Star"
			},
			{
				name: "Custom",
				value: "Custom"
			}
		],
		NumPlanes: 4,
		NumSatsPerPlane: 2,
		InterPlanePhaseIncrement: 1,
		InterPlaneTrueAnomalyIncrement: 30,
		RAANIncrement: 60,
		colorByPlane: true,
		groupName: "",
		WalkerCreateType: "single",
		WalkerCreateTypes: [{
			name: "单个对象",
			value: "single"
		}, {
			name: "分组对象",
			value: "group"
		}],
		showPath: true,
		selectEntity: function (bt, inputClass) {
			WalkerTool.selectEntity(bt, inputClass);
		},
		compute: function (data, event) {
			WalkerTool.compute(event.currentTarget);
		}
	};
	function checkEntityType(entity) {

		if (entity && entity.entityType == "satellite") {
			var propagator = CommonUtil.defaultVal(entity, "A805_Properties.propagator");
			if (propagator == "TwoBody" || propagator == "J2Perturbation") {
				return true;

			}
		}
		return false;
	}
	function getKeplerElements(entity) {
		var A805_Properties = entity.A805_Properties;
		var coordType = A805_Properties.coordType;
		var elm;
		var cbplanet = getPlanetary(entity.centralBody);
		if (coordType == "Cartesian") {
			var ces = A805_Properties.CartesianElements;
			var position = new Cesium.Cartesian3(ces.X, ces.Y, ces.Z);
			var velocity = new Cesium.Cartesian3(ces.XVelocity, ces.YVelocity, ces.ZVelocity);

			elm = Cesium.KeplerianElements.fromCartesianRV(position, velocity, cbplanet.gm);
		} else {
			var keplerianParamsValues = A805_Properties.KeplerianParams;
			var keplerianParams = new KeplerianParams(cbplanet, keplerianParamsValues);
			elm = keplerianParams.toKeplerianElements();
		}
		if (!elm) {
			return;
		}
		// SemimajorAxis	number($double)
		// example: 6878137
		// 轨道半长轴(m)

		// Eccentricity	number($double)
		// example: 0
		// 轨道偏心率

		// Inclination	number($double)
		// example: 28.5
		// 轨道倾角(deg)

		// ArgumentOfPeriapsis	number($double)
		// example: 0
		// 近地点幅角(deg)

		// RightAscensionOfAscendingNode	number($double)
		// example: 0
		// 升交点赤经(deg)

		// TrueAnomaly
		return {
			SemimajorAxis: elm.SemimajorAxis,
			Eccentricity: elm.Eccentricity,
			Inclination: Cesium.Math.toDegrees(elm.Inclination),
			ArgumentOfPeriapsis: Cesium.Math.toDegrees(elm.ArgumentOfPeriapsis),
			RightAscensionOfAscendingNode: Cesium.Math.toDegrees(elm.RightAscensionOfAscendingNode),
			TrueAnomaly: Cesium.Math.toDegrees(elm.TrueAnomaly),
			GravitationalParameter: elm.GravitationalParameter
		};
	}
	function getInitSeedEntity() {
		var entity = currentScenario.getSelectedEntity();
		if (entity && checkEntityType(entity)) {
			return entity;
		}
		var entities = currentScenario.getEntities();
		for (var i = 0; i < entities.length; i++) {
			var entity = entities[i];
			if (checkEntityType(entity)) {
				return entity;
			}
		}
	}
	var WalkerTool = {
		id: "Plugins_WalkerTool",
		menu: {
			click: function (element) {
				if (!currentScenario.dataSource) {
					layer.msg("请先新建或打开场景！");
					return;
				}
				if (!WalkerTool.isInit) {
					WalkerTool.isInit = true;
					WalkerTool.init();
				}
				var entity = getInitSeedEntity();
				if (entity && checkEntityType(entity)) {
					VModel.targeted.html = entity.name;
					VModel.targeted.value = entity.id;
				}

				const titleIcon = '<img src="plugins/WalkerTool/WalkerTool.png" style="width: 20px;height: 20px;vertical-align: text-bottom;">';
				const openNewLayerIndex = layer.open({
					type: 1,
					title: titleIcon + "Walkers星座工具",
					shadeClose: true,
					shade: false,
					area: '480px', // 宽高
					//   offset: [85+'px', ($(window).width()-480)+'px'],
					success: function (layero, index) {
					},
					content: $('#plugins_WalkerTool'),
					btn: [],
					end: function () {
					}
				});
			}
		},
		init: function () {
			Cesium.knockout.track(VModel.targeted);
			Cesium.knockout.track(VModel);
			Cesium.knockout.applyBindings(VModel, $('#plugins_WalkerTool').get(0));
		},
		selectEntity: function (bt, inputClass) {
			var id = $("." + inputClass).attr("value");
			var selectedEntity;
			if (id && id.indexOf(" ") > 0) {
				selectedEntity = {
					id: id.indexOf(" ")[0]
				}
			}
			EntityParentSelector.show({
				selectedEntity: selectedEntity,
				//				isParent:false,
				checkEntityType: checkEntityType,
				handler: function (data) {
					VModel.targeted.value = data.id;
					VModel.targeted.html = data.name;
					$("." + inputClass).attr("value", data.id);
					$("." + inputClass).html(data.name);
				},
				owner: null
			});
		},
		compute: function (bt) {
			if (WalkerTool.isStart == true) {
				layer.msg("正在计算…");
				return;
			}
			var entity = currentScenario.getEntity(VModel.targeted.value);
			if (!entity) {
				layer.msg("请选择种子卫星！");
				return;
			}
			if (!checkEntityType(entity)) {
				layer.msg("对象【" + entity.name + "】不支持Walker星座功能！");
				return;
			}
			if (VModel.WalkerCreateType == "group" && !VModel.groupName) {
				layer.msg("请输入分组名称！");
				return;
			}
			var InterPlanePhaseIncrement = parseFloat(VModel.InterPlanePhaseIncrement);
			var NumPlanes = parseInt(VModel.NumPlanes);
			if (InterPlanePhaseIncrement >= NumPlanes) {
				layer.msg("相位因子必须小于轨道面数！");
				return;
			}
			this.computeStart_(bt);
		},
		getServerInfo: function (entity) {
			var serverAPI = getWebApi("Walker");
			if (serverAPI.status == 0) {
				layer.msg(serverAPI.error);
				return;
			}
			var SeedKepler = getKeplerElements(entity);
			if (!SeedKepler) {
				layer.msg("获取种子卫星轨道参数失败！");
				return;
			}

			var url = serverAPI.url;

			var params = {
				"SeedKepler": SeedKepler,
				"WalkerType": VModel.WalkerType,
				"NumPlanes": VModel.NumPlanes,
				"NumSatsPerPlane": VModel.NumSatsPerPlane,
				"InterPlanePhaseIncrement": VModel.InterPlanePhaseIncrement,
				"InterPlaneTrueAnomalyIncrement": VModel.InterPlaneTrueAnomalyIncrement,
				"RAANIncrement": VModel.RAANIncrement,
			};
			return {
				url: url,
				params: params
			};
		},
		computeStart_: function (bt) {
			var entity = currentScenario.getEntity(VModel.targeted.value);
			var serverInfo = this.getServerInfo(entity);
			if (!serverInfo) {
				return;
			}
			$(bt).addClass("draw-bt-a");
			WalkerTool.isStart = true;
			$(bt).find(".plugins_WalkerTool_bt").html("计算中…");
			$(".plugins_WalkerTool_Results").hide();
			console.log("调用Walkers星座生成服务", serverInfo.url);
			console.log("参数", serverInfo.params);
			return PromiseUtils.postPromise({
				url: serverInfo.url,
				data: serverInfo.params
			}).then(function (result) {
				console.log("结果", result);
				if (result.IsSuccess) {
					var results = result.WalkerSatellites;
					var entityJsonPromises = [];
					var name = entity.name;
					var parentId;
					if (VModel.WalkerCreateType == "group") {
						var groupName = VModel.groupName;
						var typeInfo = entityTypeUtils.getTypeInfo("group");
						var groupData;
						if (typeInfo) {
							groupData = entityTypeUtils.getInitData({
								entityType: typeInfo.type,
							}, currentScenario.dataSource, {
								centralBody: entity.centralBody
							});
							groupData.entityType = typeInfo.type;
						}
						groupData.name = groupName;
						var oldEntity = currentScenario.getEntityByName(groupData.name);
						if (oldEntity) {
							currentScenario.removeEntity(oldEntity);
						}
						var namesIds = ProtoTreeData.getEntityNamesIds();
						var ids = namesIds.ids;
						if (!Cesium.defined(groupData.id)) {
							var type_ = CommonUtil.upperCaseFirst(groupData.entityType);
							var id = type_ + "/" + type_;
							var newId = FileUtils.createUniqueName(id, ids);
							groupData.id = newId;
						}
						parentId = groupData.id;
						entityJsonPromises.push(Promise.resolve(groupData));
					}
					var rgbaf;
					if (!VModel.colorByPlane) {
						rgbaf = Cesium.Color.pack(Cesium.Color.fromRandom({ alpha: 1 }), []);
					}
					for (var i = 0; i < results.length; i++) {
						var data = results[i];
						if (VModel.colorByPlane == true) {
							rgbaf = Cesium.Color.pack(Cesium.Color.fromRandom({ alpha: 1 }), []);
						}
						for (var j = 0; j < data.length; j++) {
							var keplerElements = data[j];
							var options = {
								parent: parentId,
								name: name + (i + 1) + (j + 1),
								color: {
									rgbaf: rgbaf
								}
							};
							if (VModel.WalkerCreateType != "group") {
								var oldEntity = currentScenario.getEntityByName(options.name);
								if (oldEntity) {
									currentScenario.removeEntity(oldEntity);
								}
							}

							var entityJsonPromise = WalkerTool.getEntityJson(keplerElements, options, entity);
							entityJsonPromises.push(entityJsonPromise);
						}

					}
					WalkerTool.importScene(entityJsonPromises, bt);
				} else {
					yyastk.msgStatusBar.add(Cesium.MsgType.ERROR, "Walkers星座工具", "请求Walkers星座生成服务：" + result.Message);
					layer.alert(result.Message);
				}
			}).catch(function (e) {
				yyastk.msgStatusBar.add(Cesium.MsgType.ERROR, "Walkers星座工具", "请求Walkers星座生成服务：" + (e.message || e));
				layer.alert(e.message || e);
			}).finally(function () {
				WalkerTool.stop(bt);
			});
		},
		getEntityJson: function (keplerElements, options, seedEntity) {
			var seedProperties = seedEntity.A805_Properties;
			var cbplanet = getPlanetary(seedEntity.centralBody);
			var KeplerianParams = [
				{ type: "semimajorAxis", value: keplerElements.SemimajorAxis },
				{ type: "eccentricity", value: keplerElements.Eccentricity },
				{ type: "inclination", value: Cesium.Math.toRadians(keplerElements.Inclination) },
				{ type: "argumentOfPeriapsis", value: Cesium.Math.toRadians(keplerElements.ArgumentOfPeriapsis) },
				{ type: "rightAscensionOfAscendingNode", value: Cesium.Math.toRadians(keplerElements.RightAscensionOfAscendingNode) },
				{ type: "trueAnomaly", value: Cesium.Math.toRadians(keplerElements.TrueAnomaly) },
				{ type: "gravitationalParameter", value: cbplanet.gm },
			];
			var ret = {
				availability: seedProperties.startTime + "/" + seedProperties.stopTime,
				entityType: "satellite",
				centralBody: seedEntity.centralBody,
				name: options.name,
				parent: options.parent,
				A805_Properties: {
					propagator: seedProperties.propagator,
					coordEpoch: seedProperties.coordEpoch,
					coordSystem: seedProperties.coordSystem,
					coordType: "Classical",
					orbitEpoch: seedProperties.orbitEpoch,
					startTime: seedProperties.startTime,
					stopTime: seedProperties.stopTime,
					stepSize: seedProperties.stepSize,
					KeplerianParams: KeplerianParams,
					Path: {
						show: VModel.showPath,
						OribtTrack: {
							Leading: { type: 'OnePass' },
							Trailing: { type: 'OnePass' }
						}
					},
					orientation: seedProperties.orientation
				},
				isSameName: true,
				path: Object.clone(currentScenario.globalAttribute.path),
				billboard: Object.clone(currentScenario.globalAttribute.billboard),
				label: Object.clone(currentScenario.globalAttribute.label),
				model: Object.clone(currentScenario.globalAttribute.model)
			};

			ret.billboard.heightReference = "NONE";
			ret.billboard.verticalOrigin = "CENTER";

			ret.label.heightReference = "NONE";
			ret.model.heightReference = "NONE";
			var entityTypeInfo = entityTypeUtils.getTypeInfo("satellite");
			if (entityTypeInfo) {
				ret.billboard.image = entityTypeInfo.icon;
				ret.model.gltf = entityTypeInfo.model;
			}
			ret.label.text = options.name;
			ret.label.fillColor = options.color;
			if (!ret.path.material) {
				ret.path.material = {};
			}
			if (!ret.path.material.solidColor) {
				ret.path.material.solidColor = {};
			}
			entityTypeUtils.setPathOnePassLeadTrail(ret);
			// ret.path.leadTime = sgp4Data.Period / 2;
			// ret.path.trailTime = sgp4Data.Period / 2;
			ret.path.material.solidColor.color = options.color;
			ret.path.show = VModel.showPath;
			return entityTypeUtils.dataHandlers.satellite.createMalkerPositionPromise(ret);
		},
		importScene: function (entityJsonPromises, bt) {
			if (entityJsonPromises.length == 0) {
				WalkerTool.stop(bt);
				return false;
			}
			Promise.all(entityJsonPromises).then(function (entityJsons) {
				var seedEntity = currentScenario.getEntity(VModel.targeted.value);
				var childSensors = [];
				if (seedEntity.children && seedEntity.children.length > 0) {
					for (var i = 0; i < seedEntity.children.length; i++) {
						var child = seedEntity.children[i];
						if (child.entityType == "sensor") {
							childSensors.push(child);
						}
					}
				}

				var namesIds = ProtoTreeData.getEntityNamesIds();
				var names = namesIds.names;
				var ids = namesIds.ids;
				for (var i = 0; i < entityJsons.length; i++) {
					var data = entityJsons[i];
					var newName = FileUtils.createUniqueName(data.name, names);
					if (data.name != newName) {
						names.push(newName);
						data.name = newName;
					}
					if (!Cesium.defined(data.id)) {
						var type_ = CommonUtil.upperCaseFirst(data.entityType);
						var id = type_ + "/" + type_;
						var newId = FileUtils.createUniqueName(id, ids);
						ids.push(newId);
						data.id = newId;
					}
				}
				var czml = entityLoad.getEntitiesCzml(entityJsons);
				var promise = ProtoTreeData.dataSource.load(czml);
				promise.then(function (dataSource) {
					var entities = dataSource.entities.values;
					if (entities.length == 0) {
						return;
					}
					for (var i = 0; i < entities.length; i++) {
						var entity = entities[i];
						var treeNode = currentScenario.addEntity(entity);
						AttitudeUtils.updateOrientation(entity, {
							centralBody: entity.centralBody,
							A805_Properties: {
								orientation: entity.A805_Properties.orientation
							}
						});
						if (childSensors.length > 0) {
							for (var j = 0; j < childSensors.length; j++) {
								var child = childSensors[j];
								var paste = entityLoad.cloneEntity(child, false);
								paste.parent = entity;
								var treeNode = currentScenario.addEntity(paste);

							}
						}
					}
					layer.msg("添加成功！");
				}).catch(function (e) {
					layer.msg(e.message || e);
				});
			}).then(function () {
				layer.msg("添加成功！");
			}).catch(function (e) {
				layer.msg(e.message || e);
			}).finally(function () {
				WalkerTool.stop(bt);
			});
		},
		stop: function (bt) {
			WalkerTool.isStart = false;
			$(bt).removeClass("draw-bt-a");
			$(bt).find(".plugins_WalkerTool_bt").html("计算");
		},
	};
	Plugins.add(WalkerTool);
})();
